package com.kkb.servlet;

import com.kkb.pojo.User;
import com.kkb.service.UserService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/signIn")
public class SignInServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");

        HttpSession session = request.getSession();
        String code_session = (String) session.getAttribute("code_session");
        if(code.equalsIgnoreCase(code_session)){
            UserService userService = new UserService();
            try {
                User user = userService.signInHandler(username, password);
                if(user != null){
                    response.sendRedirect(request.getContextPath() + "/index.jsp");
                }else{
                    wrongTipMethod(request,response,"用户名或密码错误","login.jsp");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else{
            wrongTipMethod(request,response,"验证码错误","login.jsp");
        }
    }

    private void wrongTipMethod(HttpServletRequest request, HttpServletResponse response, String tip, String page) {
        request.setAttribute("msg",tip);
        RequestDispatcher dispatcher = request.getRequestDispatcher(page);
        try {
            dispatcher.forward(request,response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
